<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8" />
		<title></title>
		<script src="js/axios.min.js" type="text/javascript" charset="utf-8"></script>
		<script src="js/adapter.js" type="text/javascript" charset="utf-8"></script>
	</head>

	<body>
		<ol>
			<li>填写自己的名称，并点击确定</li>
			<li>等待对方完成第一步</li>
			<li>填写对方的名称，并点击视频通话(仅需一方操作这一步)</li>
		</ol>
		<br /> 自己:
		<input type="text" id="me" />
		<input type="button" value="确定" onclick="login()" />
		<br /> 对方:
		<input type="text" id="you" disabled/>
		<input type="button" value="视频通话" onclick="videoCall()" />
		<br /><br />
		<video id="localVideo" autoplay muted></video>
		<input type="button" value="开始" onclick="start()" />
		<input type="button" value="停止" onclick="stop()" />
		<video id="localMediaRecorder" autoplay controls></video>
		<video id="remoteVideo" autoplay></video>
		<input type="button" value="开始" onclick="remoteStart()" />
		<input type="button" value="停止" onclick="remoteStop()" />
		<video id="remoteMediaRecorder" autoplay controls></video>
		<script type="text/javascript">
			onerror = function(msg, url, l) {
				var txt = "There was an error on this page.\n\n";
				txt += "Error: " + msg + "\n";
				txt += "URL: " + url + "\n";
				txt += "Line: " + l + "\n\n";
				txt += "Click OK to continue.\n\n";
				alert(txt);
				return true;
			};
			var me = document.getElementById("me");
			var you = document.getElementById("you");
			// 创建RTCPeerConnection对象
			var pc_config;
			var pc = new RTCPeerConnection(pc_config);
			// RTCPeerConnection对象设置本端描述时(setLocalDescription)会触发此方法
			pc.onicecandidate = function(event) {
				if(event.candidate == null) return;
				// 将自己的candidate发送给对方
				send({
					type: 'candidate',
					data: event.candidate
				});
			};
			// 成功建立连接后触发此方法
			pc.ontrack = function(event) {
				// 将对方的stream在remoteVideo中播放
				document.getElementById("remoteVideo").srcObject = event.streams[0];
			};

			// 获取自己的视频
			navigator.mediaDevices.getUserMedia({
				audio: true,
				video: true
			}).then(function(stream) {
				// 在localVideo中播放
				document.getElementById("localVideo").srcObject = stream;
				// 并将stream添加至RTCPeerConnection对象中
				stream.getTracks().forEach(function(track) {
					return pc.addTrack(track, stream);
				});
			}).catch(function(error) {
				console.log(error);
			});

			/**
			 * 填写名称后，连接webSocket
			 */
			function login() {
				me.disabled = true;
				you.disabled = false;
				// 连接webSocket
				var ws = new WebSocket('wss://' + location.host + '/webSocket/' + me.value);
				ws.onmessage = function(msg) {
					// 收到的消息格式为{type, data, sender}
					var data = JSON.parse(msg.data);
					if(data.type == 'offer') {
						// 对方向自己发起视频通话
						if(!confirm(data.sender + '邀请你进行视频通话')) {
							return;
						}
						you.disabled = true;
						you.value = data.sender;
						// 将offer设置为RTCPeerConnection对象的远端描述
						p = pc.setRemoteDescription(
							data.data
						).then(function() {
							// 创建一个answer
							return pc.createAnswer();
						}).then(function(answer) {
							// 将answer发送给对方
							send({
								type: 'answer',
								data: answer
							});
							// 并将answer设置为RTCPeerConnection对象的本端描述
							return pc.setLocalDescription(answer);
						}).catch(function(error) {
							console.log(error);
						});
					} else if(data.type == 'answer') {
						// 对方同意自己发起的视频通话
						// 将answer设置为RTCPeerConnection对象的远端描述
						pc.setRemoteDescription(data.data);
					} else if(data.type == 'candidate') {
						// 收到对方的candidate
						// 添加对方的candidate到RTCPeerConnection对象中
						pc.addIceCandidate(data.data).catch(function(error) {
							console.log(error);
						});
					}
				};
			}

			/**
			 * 发送消息给对方
			 * 
			 * @param {Object} message 消息内容
			 */
			function send(message) {
				message.sender = me.value;
				axios({
					method: 'post',
					url: '/webSocket/send',
					params: {
						message: JSON.stringify(message),
						userId: you.value
					}
				});
			}

			/**
			 * 发起视频通话
			 */
			function videoCall() {
				you.disabled = true;
				// 创建一个offer
				pc.createOffer().then(function(offer) {
					// 将offer发送给对方
					send({
						type: 'offer',
						data: offer
					});
					// 并将offer设置为RTCPeerConnection对象的本端描述
					return pc.setLocalDescription(offer);
				}).catch(function(error) {
					console.log(error);
				});
			}

			// 以下为录制视频代码，name为录制视频的名称，t为每一小块视频的时间
			var mediaRecorder;
			var chunks = [];
			var name = '';
			var remoteMediaRecorder;
			var remoteChunks = [];
			var remoteName = '';
			var t = 3000;

			function start() {
				name = me.value + '_' + you.value + '_me_' + new Date().getTime();
				// 创建一个MediaRecorder对象
				var stream = document.getElementById("localVideo").srcObject;
				mediaRecorder = new MediaRecorder(stream, {
					audioBitsPerSecond: 60000,
					videoBitsPerSecond: 1000000,
					mimeType: 'video/webm'
				});
				mediaRecorder.ondataavailable = function(e) {
					chunks.push(e.data);
					upload(e.data, name);
				};
				mediaRecorder.onstop = function(e) {
					var blob = new Blob(chunks);
					document.getElementById("localMediaRecorder").src = URL.createObjectURL(blob);
				};
				mediaRecorder.start(t);
			}

			function stop() {
				mediaRecorder.stop();
			}

			function remoteStart() {
				remoteName = me.value + '_' + you.value + '_you_' + new Date().getTime();
				// 创建一个MediaRecorder对象
				var stream = document.getElementById("remoteVideo").srcObject;
				remoteMediaRecorder = new MediaRecorder(stream, {
					audioBitsPerSecond: 60000,
					videoBitsPerSecond: 1000000,
					mimeType: 'video/webm'
				});
				remoteMediaRecorder.ondataavailable = function(e) {
					remoteChunks.push(e.data);
					upload(e.data, remoteName);
				};
				remoteMediaRecorder.onstop = function(e) {
					var blob = new Blob(remoteChunks);
					document.getElementById("remoteMediaRecorder").src = URL.createObjectURL(blob);
				};
				remoteMediaRecorder.start(t);
			}

			function remoteStop() {
				remoteMediaRecorder.stop();
			}

			function upload(blob, name) {
				var formData = new FormData();
				formData.append('file', blob);
				formData.append('name', name);
				axios({
					method: 'post',
					url: '/file/upload',
					data: formData
				});
			}
		</script>
	</body>

</html>